﻿using JunQuanPrinter.DB;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace JunQuanPrinter
{
    public partial class frmComPort : Form
    {
        private static frmComPort m_frm = null;
        private CConfigDB m_DB = CConfigDB.getClass();
        public static frmComPort getClass()
        {
            if(m_frm == null)
            {
                m_frm = new frmComPort();
            }

            return m_frm;
        }

        public frmComPort()
        {
            InitializeComponent();
            InitForm();
        }

        public static void CloseForm()
        {
            m_frm = null;
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            Close();
        }


        /// <summary>
        /// 初始化窗口
        /// </summary>
        private void InitForm()
        {
            try
            {
                CSerial serialPort = new CSerial();
                cmbComPort.Items.Clear();
                String[] lstComName = serialPort.getSerials();
                foreach(String sName in lstComName)
                {
                    cmbComPort.Items.Add(sName);
                }

                cmbBaud.Text = m_DB.getValue(CConfigDB.C_idx_Baud);
                cmbComPort.Text = m_DB.getValue(CConfigDB.C_idx_Com);
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        /// <summary>
        /// 保存数据
        /// </summary>
        /// <returns></returns>
        private Boolean SaveData()
        {
            String sComPort = cmbComPort.Text.Trim();
            String sBaud = cmbBaud.Text.Trim();
            if(sComPort.Equals(""))
            {
                MessageBox.Show("请选择串口号！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return false;
            }

            if (sBaud.Equals(""))
            {
                MessageBox.Show("请选择波特率！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return false;
            }

            try
            {
                m_DB.Upd(CConfigDB.C_idx_Com, sComPort);
                m_DB.Upd(CConfigDB.C_idx_Baud, sBaud);

            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            return true;

        }

        private void btnSave_Click(object sender, EventArgs e)
        {

            if(SaveData())
            {
                MessageBox.Show("保存成功,下次重启后生效!");
            }
        }
    }
}
